import { inject, onMounted, ref } from "vue"
import axios from "axios"
import { mapStore } from "@/stores/counter"
import { tempHttp } from "@/models/getTempHttp"
export const functionNav = () => {
    const store = mapStore()
    let scene
    let map
    let data
    let geojson_temperature
    let popup
    onMounted(async () => {
        scene = inject('$scene')
        map = inject('$map')
        const res = await tempHttp(store.selectedYear)
        const lines = res.split('\n')
        data = lines.slice(1).map(item => {
            const value = item.split(',')
            return {
                date: value[0],
                name: value[3],
                temperature: parseFloat(value[5]),
                lng: parseFloat(value[6]),
                lat: parseFloat(value[7])
            }
        })
        // 昆明温度
        const kunmingTemp = await axios.get('/src/source/气温/【下载指南】_昆明市_2001-2022年逐年平均气温.csv')
        const kunmingLines = kunmingTemp.split('\n')
        let kunmingData = kunmingLines.slice(1).map(item => {
            const value = item.split(',')
            return {
                date: value[1],
                name: value[4],
                temperature: value[6].trim(),
            }
        })
        const arr = kunmingData.map(item => parseFloat(item.temperature))
        const total = arr.reduce((sum, cur) => {
            return sum + cur
        }, 0)
        store.avg_temp = (total / 21).toFixed(2)

    })
    const temperature = async () => {
        store.isEchart=false
        store.issunItem = false
        store.istempItem = true
        store.israinyItem = false
        store.ispmItem = false
        store.isGDP = false
        store.isTemp = true
        store.isPM = false
        store.isRainy = false
        store.isSun = false
        store.isClick = true
        if (scene.getLayers().length != 0) {
            scene.removeAllLayer()
        }

        const res = await tempHttp(store.selectedYear)
        const lines = res.split('\n')
        data = lines.slice(1).map(item => {
            const value = item.split(',')
            return {
                date: value[0],
                name: value[3],
                temperature: parseFloat(value[5]).toFixed(2),
                lng: parseFloat(value[6]),
                lat: parseFloat(value[7])
            }
        })

        let tempData_High = data.sort((a, b) => b.temperature - a.temperature).slice(0, 5)
        let tempData_Low = data.sort((a, b) => a.temperature - b.temperature).slice(0, 5)

        // 绘图
        store.tempItem_option = {
            title: {
                text: `${store.selectedYear}年平均气温最高地区`,
                left: 'center',
                top: '10%',
                textStyle: {
                    color: '#fff',

                },
            },
            dataset: {
                source: [
                    ['date', 'temperature', 'name'],
                    ...tempData_High.map(item => [item.year, item.temperature, item.name])
                ]
            },
            grid: {
                left: '20%',
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                name: 'temperature', axisLabel: {
                    color: '#fff'
                }
            },
            yAxis: {
                type: 'category', axisLabel: {
                    color: '#fff'
                }
            },
            series: [
                {
                    type: 'bar',
                    encode: {
                        x: 'temperature',
                        y: 'name'
                    },
                    itemStyle: {
                        color: '#ff2d51'
                    }
                }
            ]
        };
        store.tempItem_option_low = {
            title: {
                text: `${store.selectedYear}年平均气温最底地区`,
                left: 'center',
                top: '10%',
                textStyle: {
                    color: '#fff',

                },
            },
            dataset: {
                source: [
                    ['date', 'temperature', 'name'],
                    ...tempData_Low.map(item => [item.year, item.temperature, item.name])
                ]
            },
            grid: {
                left: '20%',
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                name: 'temperature', axisLabel: {
                    color: '#fff'
                }
            },
            yAxis: {
                type: 'category', axisLabel: {
                    color: '#fff'
                }
            },
            series: [
                {
                    type: 'bar',
                    encode: {
                        x: 'temperature',
                        y: 'name'
                    },
                    itemStyle: {
                        color: 'lightblue'
                    }
                }
            ]
        };


        // 转为geojson
        geojson_temperature = {
            type: 'FeatureCollection',
            features: data.map(item => ({
                type: 'Feature',
                geometry: {
                    type: "Point",
                    coordinates: [item.lng, item.lat]
                },
                properties: {
                    name: item.name,
                    date: item.date,
                    temp: item.temperature
                }
            }))
        }

        const pointLayer = new L7.PointLayer({ depth: false })
            .source(geojson_temperature)
            .shape('cylinder')
            .size('temp', function (level) {
                return [3, 1, level * 4 + 20];
            })
            .animate(true)
            .active(true)
            .color('#006CFF')
            .style({
                opacity: 0.8,
                sourceColor: 'red',
                targetColor: 'yellow',
                lightEnable: false,
            });

        pointLayer.on('mousemove', (e) => {
            const temp = e.feature.properties.temp.toFixed(2)
            popup = new L7.Popup({
                offsets: [0, 0],
                closeButton: false,
            })
                .setLnglat(e.lngLat)
                .setHTML(`<span>${e.feature.properties.date}年</br>${e.feature.properties.name}: ${temp}℃</span>`);
            scene.addPopup(popup);
        });
        pointLayer.on('mouseout', () => {
            scene.removePopup(popup)
        })
        scene.addLayer(pointLayer);
    }

    // 提供一个方法来更新选定的年份
    const renderTemp = () => {
        // 每次选定年份更新后，重新加载对应年份的数据
        temperature();
    }

    return {
        temperature,
        renderTemp,
        data
    }
}